<template>
  <div class="main_container">
    <div class="title">
      <div class="title-top">
        <h2>记录管理 </h2>
        <el-select v-model="selectedYear" class="m-2 " placeholder="请选择" size="large" @change="handleYearChange" v-if="!isMobile">
          <el-option v-for="item in optionsYear" :key="item.value"
            :label="item.ACADEMICYEAR + '学年&nbsp;&nbsp;' + item.SEMESTER_NAME" :value="item.SEMESTER_ID" />
        </el-select>
      </div>
      <p>管理您的所有成长记录，包括添加、编辑和删除操作</p>
    </div>
    <!-- 顶部导航区域 -->
    <tabs :tabList="tabList"  @add-record-click="showAddModal" @select-change="handleSelectChange"  :selected-value="currentSelectedValue" />

    <!-- 顶部卡片区域 -->
    <!-- <record-cards :cardList="cardList" :cardQuery="cardQuery" /> -->

    <!-- 表格模块 -->
    <el-row :gutter="20" style="margin: 20px 0;">
      <el-col :span="24" style="padding: 0;">
        <table-module :tableQuery="tableQuery" @delete-item="handleDelete" @row-click="handleRowClick"
          @update-visible="updateVisible" />
      </el-col>
    </el-row>

    <!-- 添加记录模态框 -->
    <AddRecordModal v-model:visible="addModalVisible" @save-success="onAddRecordSuccess" />

    <!-- 成长记录详情对话框 -->
    <GrowthRecordDialog v-model:visible="recordDialogVisible" :basic-info="selectedRecordBasicInfo"
      :growth-record="selectedGrowthRecord" :proof-material="selectedProofMaterial"
      />
  </div>
</template>

<script setup>
import { reactive, ref, computed, onMounted, onUnmounted, defineEmits } from "vue";
import { useStore } from '@/store';
import tabs from "@/components/tabs.vue";
import recordCards from "@/components/record-cards.vue";
import tableModule from "@/components/table-module.vue";
import AddRecordModal from "@/components/AddRecordModal.vue";
// 导入API
import { getSummary } from '@/api/home.js';
// 引入封装的弹窗组件
import GrowthRecordDialog from '@/components/GrowthRecordDialog.vue'

import { useRoute } from 'vue-router';
const route = useRoute();
const store = useStore();
const userInfo = computed(() => store.user.userInfo);
const recordStore = store.record;
const homeStore = store.home;


// 添加记录模态框的显示状态
const addModalVisible = ref(false);

// 检测是否为移动设备
const isMobile = ref(false);

const checkDeviceType = () => {
  const width = window.innerWidth;
  isMobile.value = width < 768; // 768px为断点
};

const updateVisible = (visible) => {
  addModalVisible.value = visible;
}

let cardList = reactive([{ title: '所有类型', value: '所有类型' }]);

let tabList = [
  { label: '添加新纪录', value: 'all', type: 'button' },
  {
    label: '所有类型',
    value: 'pending',
    type: 'select',
    optionsList: []
  }
];
// 显示添加记录模态框
const showAddModal = () => {
  addModalVisible.value = true;
};



// 仪表盘卡片数据
const getSummaryData = () => {
  cardList = [{ title: '所有类型', value: '所有类型' }];
  getSummary().then(res => {
    const { code, data } = res;
    if (code > 0) {
      cardList = [...cardList, ...data];
      tabList[1].optionsList = [...cardList];
    }
  }).catch(err => {
    console.log(err);
  });
};


let selectedYear = ref('');
let optionsYear = reactive([])
// 定义响应式变量来存储当前选中的值
let currentSelectedValue = ref(''); // 默认值设为'所有类型'

// 下拉框类型筛选
// 修改handleSelectChange方法，传入当前分页参数
const handleSelectChange = (value) => {
  // 调用list页面专用的筛选方法，传入当前分页参数
  recordStore.setListPageFilterType(value === '所有类型' ? 'all' : value, tableQuery.page, tableQuery.size);
  // 更新当前选中的值
  currentSelectedValue.value = value;
};

// 修改表格数据参数，让list使用分页后的数据
let tableQuery = reactive({
  page: 1,
  size: 5,
  total: computed(() => recordStore.filters.listPage.filteredTotal),
  small: true,
  title: '个人经历',
  // 使用list页面专用的分页后数据
  list: computed(() => recordStore.filters.listPage.paginatedRecords),
  isLoading: recordStore.isLoading,
  cz: true,
  columns: [
    { prop: 'EVALRECORD', label: '记录标题', width: '160' },
    { prop: 'PARENT_NAME', label: '类型', width: '100' },
    { prop: 'TJRQ', label: '日期', width: '120' },
    { prop: 'FLAG', label: '状态', width: '100' }
  ]
});

// 修改handleYearChange方法，传入当前分页参数
const handleYearChange = async (year) => {
   // 调用设置学期id的action
  recordStore.setSemesterId(year);
  selectedYear.value = year;

  await recordStore.fetchRecords(year, tableQuery.page, tableQuery.size);
  // 刷新当前页数据
  recordStore.setListPagePaginatedRecords(tableQuery.page, tableQuery.size);
}



// 修改onAddRecordSuccess方法，传入当前分页参数
const onAddRecordSuccess = () => {
  // 添加成功后刷新列表数据，保持当前分页
  recordStore.fetchRecords(selectedYear.value || undefined, tableQuery.page, tableQuery.size);
};

// 处理表格查询参数更新事件
const handleTableQueryUpdate = (newValue) => {
  tableQuery.page = newValue.page;
  tableQuery.size = newValue.size;
  // 重新设置分页数据
  recordStore.setListPagePaginatedRecords(newValue.page, newValue.size);
}
// 在setup中添加emit
const emit = defineEmits(['update:tableQuery']);

// 删除记录处理函数
const handleDelete = async (id) => {
  await recordStore.deleteRecord(id);
};
// 成长记录对话框相关数据
let recordDialogVisible = ref(false);
let selectedRecordBasicInfo = ref({});
let selectedGrowthRecord = ref({});
let selectedProofMaterial = ref('');
// 处理表格行点击事件
const handleRowClick = (row) => {
    // 打开对话框
  recordDialogVisible.value = true;
  // 这里需要根据实际数据结构进行调整
  // 假设row包含了记录的基本信息和详细信息
  selectedRecordBasicInfo.value = {
    name: userInfo.value.username || '',
    school: '郑州根杨外国语学校', // 假设这是学校信息
    semester: '2024-2025学年第一学期', // 可以从store或API获取
    idCard: '527441418993159988', // 这里应该是学生真实信息
    studentCode: '', // 学生标识码
    parent_name: row.PARENT_NAME,
    evalrecord: JSON.parse(row.EVALRECORD),
  };
  
  // 构建成长记录数据
  selectedGrowthRecord.value = row
  
  // 设置证明材料图片（如果有的话）
  // 这里假设row中有相关图片信息
  selectedProofMaterial.value = ''; // 实际项目中应该有真实的图片路径
};

// 在emit中添加handleTableQueryUpdate事件处理
onMounted(async () => {
    //学期赋值
  optionsYear = toRaw(homeStore.semesterInfo).reverse();
  selectedYear.value = homeStore.semesterInfo[1].SEMESTER_ID;
  // 获取仪表盘卡片数据
  getSummaryData();
  // 调用API获取数据
  recordStore.fetchRecords(selectedYear.value || undefined);
  // 检测设备类型
  checkDeviceType();
  window.addEventListener('resize', checkDeviceType);
  // 监听tableQuery更新事件
  emit('update:tableQuery', handleTableQueryUpdate);
  // 检查路由查询参数，如果有title则触发筛选
  if (route.query.title) {
    // 延迟一小段时间确保tabList已加载完成
    setTimeout(() => {
      handleSelectChange(route.query.title);
      handleSelectChange(route.query.title);
    }, 100);
  }
});

onUnmounted(() => {
  window.removeEventListener('resize', checkDeviceType);
});
</script>

<style scoped lang="scss">
.main_container {
  width: 100%;
  max-width: 1450px;
  margin: 0 auto;
  padding: 0;

  .title {
    max-width: 1420px;
    margin: 10px auto;
    .title-top {
      height: 33px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin: 10px 0;
      h2 {
        font-size: 24px;
        font-weight: 800;
        margin: 10px 0;
      }
      p{
        color: #4B5563;
      }
      .el-select {
        width: 310px;
      }
    }
  }
}
</style>
